import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:tencent_cloud_chat_demo/db/custom_sticker.dart';
import 'package:tencent_cloud_chat_demo/utils/path.dart';
import 'package:tencent_cloud_chat_demo/utils/request.dart';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as p;
import 'package:tencent_cloud_chat_demo/utils/toast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'api/sticker.dart';
import 'authService.dart';

// 上传头像
Future<String?> uploadAvatar({
  bool isRegister = false,
}) async {
  try {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(
      source: ImageSource.gallery,
    );
    if (pickedFile == null) return null;

    final CroppedFile? croppedFile = await ImageCropper().cropImage(
      sourcePath: pickedFile.path,
      uiSettings: [
        AndroidUiSettings(
          toolbarTitle: '裁剪头像',
          toolbarColor: Colors.deepOrange,
          initAspectRatio: CropAspectRatioPreset.original,
          lockAspectRatio: false,
        ),
        IOSUiSettings(
          title: '裁剪头像',
        ),
      ],
      compressFormat: pickedFile.path.endsWith('.png')
          ? ImageCompressFormat.png
          : ImageCompressFormat.jpg,
    );
    if (croppedFile?.path == null) {
      return null;
    }
    final beforeFile = File(croppedFile!.path);
    final finalFile = await compressImageToTargetSize(
      beforeFile,
      pickedFile.path.endsWith('.png') ? '.png' : '.jpg',
    );

    final userSig = await AuthService.getAuthToken();

    debugPrint("Picked file path: ${finalFile!.path}");
    final file = File(finalFile.path);
    debugPrint("File size: ${file.lengthSync()} bytes");
    FormData formData;
    if (isRegister) {
      formData = FormData.fromMap({
        "file": await MultipartFile.fromFile(
          finalFile.path,
        ),
      });
    } else {
      formData = FormData.fromMap({
        "usersig": userSig,
        "file": await MultipartFile.fromFile(
          finalFile.path,
        ),
      });
    }
    EasyLoading.show(status: '头像上传中...');
    final res = await appRequest(
      method: 'post',
      path: isRegister
          ? 'https://yunpengim.daboluo.pro/api/user/avatar_file'
          : 'https://yunpengim.daboluo.pro/api/user/avatar',
      data: formData,
      contentType: 'multipart/form-data',
    );
    // 打印整个响应
    print('上传头像参数: $formData');
    print('上传头像响应: $res');

    if (res.data?['code'] == 1) {
      debugPrint("Response用户头像上传成功: $res");
      ToastUtils.toast('用户头像上传成功');
      return res.data?['data']['url'];
    }
  } catch (error) {
    debugPrint("Error: $error");
    ToastUtils.toast("网络故障，请稍后重试");
  } finally {
    EasyLoading.dismiss();
  }
  return null;
}

Future<void> pickAndCompressWechatStyleEmoji() async {
  final picker = ImagePicker();
  final pickedFile = await picker.pickImage(
    source: ImageSource.gallery,
  );
  if (pickedFile == null) return;

  // final rawBytes = await pickedFile.readAsBytes();
  // final decoded = img.decodeImage(rawBytes);
  // if (decoded == null) return null;

  // 缩放至 120x120（等比例缩放到最大边为 120）
  // final resized = img.copyResize(
  //   decoded,
  //   width: 120,
  //   interpolation: img.Interpolation.average,
  // );

  // // 编码为 PNG（压缩质量默认即可，PNG 为无损）
  // final compressedBytes = img.encodePng(resized);

  // // 保存路径
  final customDir = Directory('${AppPath.documentPath}/customsticker');
  if (!await customDir.exists()) {
    await customDir.create(recursive: true);
  }

  final String fileName;
  if (pickedFile.path.endsWith('.png')) {
    fileName = 'sticker_${DateTime.now().millisecondsSinceEpoch}.png';
  } else {
    fileName = 'sticker_${DateTime.now().millisecondsSinceEpoch}.jpg';
  }
  // final savedFile = File('${customDir.path}/$fileName');

  // final file =
  //     await savedFile.writeAsBytes(Uint8List.fromList(compressedBytes));
  // await insertEmoji(file.path, keywords: fileName);

  final CroppedFile? croppedFile = await ImageCropper().cropImage(
    sourcePath: pickedFile.path,
    uiSettings: [
      AndroidUiSettings(
        toolbarTitle: '裁剪表情',
        toolbarColor: Colors.deepOrange,
        initAspectRatio: CropAspectRatioPreset.original,
        lockAspectRatio: false,
      ),
      IOSUiSettings(
        title: '裁剪表情',
      ),
    ],
    compressFormat: pickedFile.path.endsWith('.png')
        ? ImageCompressFormat.png
        : ImageCompressFormat.jpg,
  );
  if (croppedFile?.path == null) {
    return;
  }

  final file = File(croppedFile!.path);
  var result = await FlutterImageCompress.compressAndGetFile(
    file.absolute.path,
    AppPath.resolveEmojiPath(fileName),
    quality: 10,
    format: pickedFile.path.endsWith('.png')
        ? CompressFormat.png
        : CompressFormat.jpeg,
  );
  if (result?.path == null) {
    return;
  }
  final beforeFile = File(result!.path);
  final finalFile = await compressImageToTargetSize(
      beforeFile, pickedFile.path.endsWith('.png') ? '.png' : '.jpg');
  if (finalFile?.path == null) {
    return;
  }
  await addSticker(finalFile!.path, fileName);

  return;
}

Future<void> addSticker(String path, String fileName) async {
  final res = await CustomSitckerAPI.addSticker(path, fileName);
  await insertEmoji(
    path,
    int.parse(res?['id']),
    keywords: fileName,
  );
  ToastUtils.toast('表情收藏成功');
}

Future<List<File>> getCustomStickerImages() async {
  final appDir = await getApplicationDocumentsDirectory();
  final customStickerDir = Directory('${appDir.path}/customsticker');

  if (!await customStickerDir.exists()) return [];

  // 获取所有图片文件（你也可以加个过滤，例如只选 .png）
  final files = customStickerDir
      .listSync()
      .whereType<File>()
      .where((file) =>
          file.path.endsWith('.png') ||
          file.path.endsWith('.jpg') ||
          file.path.endsWith('.jpeg'))
      .toList();

  return files;
}

class Urlss {
  Urlss({
    required this.url,
    required this.name,
    this.createdAt,
    this.fileId,
  });

  final String url;
  final String name;
  final int? createdAt;
  final int? fileId;
}

Future<List<Urlss>> downloadEmojisToCustomStickerDir(
    List<Urlss> emojiUrls) async {
  final List<Urlss> files = [];

  for (Urlss emojiUrl in emojiUrls) {
    try {
      // 获取文件名，比如 from https://xxx.com/a.png => a.png
      // final filename = p.basename(Uri.parse(url).path);

      // 创建临时文件完整路径
      final filePath = AppPath.resolveEmojiPath(emojiUrl.name);
      final file = File(filePath);
      files.add(Urlss(
        url: filePath,
        name: emojiUrl.name,
        createdAt: emojiUrl.createdAt,
        fileId: emojiUrl.fileId,
      ));
      // 如果文件已存在，可以跳过下载（可选）
      if (!file.existsSync()) {
        final response = await http.get(Uri.parse(emojiUrl.url));
        if (response.statusCode == 200) {
          await file.writeAsBytes(response.bodyBytes);
        } else {
          continue;
        }
      }
    } catch (e) {
      debugPrint('⚠️ 处理 ${emojiUrl.url} 出错: $e');
    }
  }

  return files;
}

Future<File?> compressImageToTargetSize(File file, String format,
    {int maxSizeInBytes = 512 * 1024}) async {
  final tempDir = await getTemporaryDirectory();
  String targetPath = p.join(
    tempDir.path,
    "compressed_${DateTime.now().millisecondsSinceEpoch}$format",
  );

  int quality = 90;
  File? result;

  while (quality > 10) {
    final compressedBytes = await FlutterImageCompress.compressWithFile(
      file.absolute.path,
      quality: quality,
      format: CompressFormat.jpeg,
    );

    if (compressedBytes == null) break;

    if (compressedBytes.lengthInBytes <= maxSizeInBytes) {
      result = await File(targetPath).writeAsBytes(compressedBytes);
      break;
    }

    quality -= 10;
  }

  return result;
}
